// pages/chat/index.js
import {rongId} from '../../config'
const app = getApp();
const { RongIMLib } =app.globalData
import {$await,timeAgo} from '../../utils/util'
import runtime from '../../utils/runtime'
import {imgUrlAvatar,imgUrlImg} from '../../config'
import {playbackAPI} from '../../api/playback/index'
import {commonAPI} from '../../api/common/index'
import face from '../../utils/emoji'
const img_url = 'https://images.weserv.nl/?url='
const face_online_path = "https://images.weserv.nl/?url=https://img001.cbct.cn/image/face/"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 表情包
    faceList:face.map(item => ({...item,url:`${face_online_path}${item.url}`})),
    inputBottom:0,
    _keyboardShow:false,
    emoji:false,
    focus:false,
    hostList:[],
    adList:[],
    showAD:false,
    chatAreaHeight:0, // 聊天区域的高
    toView:'scroll0',//滚动ID
    playInfo:{},
    isplay:false,
    history:[],
    msgContent:'',
    playerStatus:false,
  },
  setEmoji({detail}){
    let {msgContent} = this.data
    msgContent+=detail
    this.setData({msgContent})
  },
  showEmoji(){
    this.setData({emoji:this.data._keyboardShow || !this.data.emoji})
    wx.nextTick(()=>{
      let query = this.createSelectorQuery().in(this)
      query.select('#emoji').boundingClientRect()
      query.exec((rect)=>{
        this.setData({
          inputBottom:rect[0].height,
          focus:false
        })
      })
    })
  },
  deleteEmoji() {
    const pos = Number(this.data.msgContent.length)
    const comment = this.data.msgContent
    let result = '',
      cursor = 0

    let emojiLen = 6
    let startPos = pos - emojiLen
    if (startPos < 0) {
      startPos = 0
      emojiLen = pos
    }
    const str = comment.slice(startPos, pos)
    const matchs = str.match(/\[([\u4e00-\u9fa5\w]+)\]$/g)
    // 删除表情
    if (matchs) {
      const rawName = matchs[0]
      const left = emojiLen - rawName.length
      const emojiNames = this.data.faceList.map(item => (item.content))
      if (emojiNames.indexOf(rawName) >= 0) {
        const replace = str.replace(rawName, '')
        result = comment.slice(0, startPos) + replace + comment.slice(pos)
        cursor = startPos + left
      }
      // 删除字符
    } else {
      let endPos = pos - 1
      if (endPos < 0) endPos = 0
      const prefix = comment.slice(0, endPos)
      const suffix = comment.slice(pos)
      result = prefix + suffix
      cursor = endPos
    }
    this.setData({
      msgContent: result,
      // cursor: cursor
    })
  },
  onkeyboardHeightChange(e) {
    const {height} = e.detail
    wx.nextTick(()=>{
      this.setData({
        inputBottom: height
      })
    })
  },
  bindblur(e){
    this.data._keyboardShow = false
    wx.nextTick(()=>{
      setTimeout(() => {
        if(!this.data.emoji){
          this.setData({
            focus:false
          },()=>{
            this.setData({inputBottom:0})
          })
        }
      }, 0);
    })
  },
  bindfocus(e){
    this.data._keyboardShow = true
    this.setData({
      emoji:false,
      focus:true
      // inputBottom:e.detail.height
    })
  },
  computedHeight(){
    let query = wx.createSelectorQuery().in(this)
    query.select('.chat').boundingClientRect()
    query.select('.send_msg').boundingClientRect()
    query.exec((rect)=>{
      let chat = rect[0].height
      let input = rect[1].height
      let chatAreaHeight = (chat - input).toFixed(2)
      this.setData({chatAreaHeight})
    })
  },
  displayPlayer(){
    this.setData({playerStatus:!this.data.playerStatus})
  },
  refersh(){
    this.onLoad(this.options)
  },
  closeAD(){
    this.setData({showAD:true})
    wx.nextTick(()=>{
      this.computedHeight()
    })
  },
  async sendMsg(){
    let userInfo = wx.getStorageSync('userInfo')
    if(!userInfo && !userInfo.token){
      return wx.navigateTo({
        url:'/pages/login/login'
      })
    }
    let {number,period,play_id} = this.data.playInfo
    let params = {
      number,
      period,
      comment: this.data.msgContent,
      play_id
    }
    let [err,res] = await $await(playbackAPI.playSendMsg(params))
    if(res){
      this.setData({
        msgContent:'',
        focus:false,
        emoji:false
      })
      setTimeout(() => {
        this.historyMsg()
      }, 1000);
    }
  },
  // 关注
  async follow({currentTarget:{dataset:{id}}}){
    let params = {
      obj_id:id,
      type:1
    }
    let [err,res] = await $await(commonAPI.follow(params))
    if(res){
      this.getHosts()
    }
  },
  // 进入录播间
  async enterPlay(play_id){
    let [err,res] = await $await(playbackAPI.enter({play_id}))
    if(res){
      res = {
        ...res,
        out_image:img_url+imgUrlImg+res.out_image,
        programme_hosts:res.programme_hosts.map(item => {
          return {
            ...item,
            avatar:img_url+imgUrlAvatar+item.avatar
          }
        })
      }
      this.setData({playInfo:res})
      this.getHosts()
      this.historyMsg()
      this.adList(res.number)
    }
  },
  // 获取广告位
  async adList(id){
    let params = {
      position:4,
      type:2,
      ditch:id
    }
    let [err,res] = await $await(playbackAPI.adList(params))
    if(res){
      res.banner.length>0 && res.banner.forEach(item =>{
        item.image = img_url+item.image
        if(item.jump_type!=1){
          item.url = ''
        }
      })
      this.setData({adList:res.banner})
      wx.nextTick(()=>{
        this.computedHeight()
      })
    }
  },
  jumpAd({currentTarget:{dataset:{info}}}){
    if(info.jump_type == 1){
      wx.navigateTo({
        url: `/pages/webview/webview?webURL=${info.url}`
      });
    }
  },
  // 获取主持人列表
  async getHosts(){
    let [err,res] = await $await(playbackAPI.getHosts({id:this.data.playInfo.play_id,live_type:0}))
    if(res){
      let hostList = Object.values(res).map(item =>{
        return {
          ...item,
          avatar_url:img_url+item.avatar_url
        }
      })
      this.setData({hostList})
    }
  },
  // 历史消息
  async historyMsg(){
    let {number,period,play_id} = this.data.playInfo
    let params = {
      number,
      period,
      play_id,
      page:1
    }
    let [err,res] = await $await(playbackAPI.history({...params}))
    if(res){
      
      res.item = res.item && res.item.map(item =>{
        return {
          ...item,
          avatar:img_url+imgUrlAvatar+item.avatar
        }
      })
      // 表情处理
      this.data.faceList.forEach((item)=>{
        res.item.forEach(m =>{
          if(m.content.indexOf(item.content)!=-1){
            m.content = m.content.replaceAll(
              item.content,
              `<img class="face_msg" src="${item.url}"/>`
              )
          }
        })
      })
      this.setData({
        history:res.item,
        toView:`scroll${res.item.length-1}`
      })
      
    }
  },
  play(){
    this.videoContext.play()
    this.setData({isplay:true})
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.options.play_id = options.play_id
    this.enterPlay(options.play_id)
    // 获取到video实例
    this.videoContext = wx.createVideoContext('playback',this)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})